package mapReduce.homework.q4_getTotalMoney;

import mapReduce.util.JobSubmit;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;

import java.io.IOException;

public class GetTotalMoneyByPartnerApp {
    public static class gtmbpMapper extends Mapper<LongWritable,Text,Text,DoubleWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] fields = line.split("\t");
            //获得其中有用字段
            String partner = fields[2];
            String year = fields[0];
            double money = Double.parseDouble(fields[4]);

            //合作方和年份统一作为key
            context.write(new Text(year+"\t"+partner),new DoubleWritable(money));
        }
    }

    public static class gtmbpReducer extends Reducer<Text,DoubleWritable,Text,DoubleWritable>{
        @Override
        protected void reduce(Text key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException {
            double sum = 0;
            for(DoubleWritable value:values){
                sum += value.get();
            }

            context.write(key,new DoubleWritable(sum));
        }

    }

    public static void main(String[] args) throws Exception {
        JobSubmit.submitBaseJob(
                GetTotalMoneyByPartnerApp.class,
                args,
                4,
                GetTotalMoneyByPartnerPartitioner.class,
                SequenceFileOutputFormat.class);
    }
}
